<template>
  <el-upload
    v-loading="loading"
    class="uploader"
    :class="{ 'hover-mask': value }"
    :action="`${baseURL}upload/uploadFile`"
    :show-file-list="false"
    :on-success="handleSuccess"
    :before-upload="handlebeforeUpload"
  >
    <img v-if="value" :src="value" class="avatar" />
    <i class="el-icon-plus uploader-icon"></i>
  </el-upload>
</template>

<script>
  export default {
    props: {
      value: String,
      required: true
    },
    data() {
      return {
        loading: '',
        baseURL: process.env.VUE_APP_BASE_API
      }
    },
    methods: {
      handleSuccess(res, file) {
        this.loading = false
        const { data } = res
        if (data.fileUrl) {
          const imageUrl = data.fileUrl
          // 触发事件 input，父组件会修改绑定的 value 值
          this.$emit('input', imageUrl)
        }
      },
      handlebeforeUpload(file) {
        // 这里做可以做文件校验操作
        const isImg = /^image\/\w+$/i.test(file.type)
        if (!isImg) {
          this.$message.error('只能上传 JPG、PNG、GIF 格式!')
          return false
        }
        this.loading = true
      }
    }
  }
</script>

<style scoped lang="scss">
  .uploader {
    width: 130px;
    height: 130px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    &:hover {
      border-color: #409eff;
    }
    /deep/ .el-upload {
      position: relative;
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
  }
  .uploader-icon {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    line-height: 128px;
    text-align: center;
    font-size: 28px;
    color: #8c939d;
  }
  .avatar + .uploader-icon {
    opacity: 0;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
    border-radius: 6px;
  }
  .hover-mask:hover .uploader-icon {
    opacity: 1;
    background-color: rgba(0, 0, 0, 0.2);
    color: #fff;
  }
</style>
